package test3.backtracking;

import java.util.ArrayList;
import java.util.List;

/**
 * 77.组合
 * 给定两个整数 n 和 k，返回 1 ... n 中所有可能的 k 个数的组合。
 */
public class Combine {
    private List<List<Integer>> lists = new ArrayList<>();
    private List<Integer> list = new ArrayList<>();

    public static void main(String[] args) {
        Combine combine = new Combine();
        combine.combine(4, 2);
        for (List<Integer> list : combine.lists) {
            for (Integer item : list) {
                System.out.print(item);
            }
            System.out.println();
        }
    }

    public List<List<Integer>> combine(int n, int k) {
        combine(n, k, 0);
        return lists;
    }

    public void combine(int n, int k, int index) {

        if (index == k) {
            lists.add(new ArrayList<>(list));
            return;
        }

        for (int i = index + 1; i <= n; i++) {
            if (list.size() > 0 && list.get(list.size() - 1) >= i) continue;
            list.add(i);
            combine(n, k, index + 1);
            list.remove(list.size() - 1);
        }
    }

}
